import pickle
import socket
import time


class SockerBase:
    ge = b'#*#*#*#'
    messages = list()
    buffer = b''

    def __init__(self, ip='127.0.0.1', port=50000, conn=None):
        """ 初始化一个可以接受发送的对象，可以直接提供一个conn，直接创建好连接
        或者再使用两个init函数，建立连接"""
        if conn is None:
            self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
            self.socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
            self.ip, self.port = ip, port
        else:
            self.init_conn(conn)

    def init_conn(self, conn):
        self.id = 'Connection'
        self.conn = conn

    def init_server(self, max=1):
        """ 初始化一个服务器，开启监听 """
        self.id = 'Servier'
        self.socket.bind(('127.0.0.1', self.port))
        self.socket.listen(max)

    def start_listen(self):
        sc, sockname = self.socket.accept()
        self.conn = sc
        return sc

    def init_client(self):
        """ 初始化一个客户端，并且连接到特定端口 """
        self.id = 'Client'
        self.socket.connect((self.ip, self.port))
        self.conn = self.socket

    def print(self, *args):
        """ 加上特殊的头，把内容打印出来 """
        print('{}: '.format(self.id), *args)

    def mysend(self, information):
        """ 传输一个对象，以及分隔符 """
        self.conn.sendall(self.ge)
        self.conn.sendall(pickle.dumps(information))
        self.conn.sendall(self.ge)
        # self.print('Rece : {}'.format(information))

    def myrece(self):
        """ 阻塞地接受一个对象 """
        while True:
            if len(self.messages) == 0:
                time.sleep(0.1)
                self._try_recive()
            else:
                temp = self.messages.pop(0)
                # print('pop',self.messages,'temp:',temp)
                return temp

    def _try_recive(self):       # 尝试获得信息，并存入butter
        time.sleep(0.1)
        data = self.conn.recv(1024*512)
        if data != b'':
            self._message_to_messages(data)
            return True

    def _message_to_messages(self, data): # 分割字符串，存在messages列表
        self.buffer += data
        # print(len(self.buffer))
        # print(len(self.buffer)/1024)
        # self.print('present buffer: {}'.format(self.buffer))
        for i in range(self.buffer.count(self.ge)//2):
            self.buffer = self.buffer.replace(self.ge, b'', 1)
            message, self.buffer = self.buffer.split(self.ge, 1)
            # print('message', len(message), self.buffer)
            message = pickle.loads(message)
            self.messages.append(message)
        # self.print('present messages: {}'.format(self.messages))
